#!/bin/sh

# Copyright (c) 2014-2025 Franco Fichtner <franco@opnsense.org>
# Copyright (c) 2004-2010 Scott Ullrich <sullrich@gmail.com>
# Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

TMPPERM=01777
TMPDIRS="
/var/lib/php/tmp
"

USE_MFS_TMP=$(/usr/bin/grep -c 'use_mfs_tmp[^_]' /conf/config.xml)

# see if / is writable (aka. not a live media boot)
if _tmpdir=$(mktemp -d -q /.diskless.XXXXXX); then
	# in this mode we are allowed to clear /tmp
	TMPDIRS="/tmp ${TMPDIRS}"
	rmdir ${_tmpdir}
else
	# disable to avoid spurious /tmp mount
	USE_MFS_TMP=0
fi

for TMPDIR in ${TMPDIRS}; do
	mkdir -p ${TMPDIR}
	find ${TMPDIR} -mindepth 1 -maxdepth 1 -exec rm -rf {} \;
	chmod ${TMPPERM} ${TMPDIR}
done

if [ ${USE_MFS_TMP} -ne 0 ]; then
	MAX_MFS_TMP=$(grep 'max_mfs_tmp' /conf/config.xml | sed 's/[^>]*>\([^<]*\)<.*/\1/')
	MAX_MEM_SYS=$(sysctl -n hw.physmem)

	if [ -z "${MAX_MFS_TMP}" ]; then
		# cap to 50% by default to avoid swapping
		MAX_MFS_TMP=50
	fi

	TMP_SIZ=$((MAX_MEM_SYS / 100 * MAX_MFS_TMP))

	for TMPDIR in ${TMPDIRS}; do
		mount -t tmpfs -o mode=${TMPPERM},size=${TMP_SIZ} tmpfs ${TMPDIR}
	done
fi
